package ordinaryArray;

import java.util.Arrays;
import java.util.Comparator;

/**
 * @author kunkun
 * @className LeetCode_56
 * @Description 合并区间
 * @date 2025/3/4 18:11
 */
public class LeetCode_56 {

    public int[][] merge(int[][] intervals) {
        return solution_1(intervals);
    }

    public static void main(String[] args) {
        LeetCode_56 object = new LeetCode_56();
//        object.print(object.merge(new int[][]{{1,3},{2,6},{8,10},{15,18}}));
        object.print(object.merge(new int[][]{{1,4},{2,3}}));
    }

    public void print(int[][] intervals){
        for (int i = 0; i < intervals.length; i++) {
            System.out.print("[");
            for (int j = 0; j < intervals[i].length; j++) {
                System.out.print(intervals[i][j]+" ");
            }
            System.out.println("]");
        }
    }

    /**
    * @Description: 排序+逐个遍历
    * @Author: kunkun
    * @Date:  2025/3/4 18:20
    * @Parameters:
    * @Return
    * @Throws
    */
    public int[][] solution_1(int[][] intervals){
        //0. 特殊情况返回
        if (intervals.length<=1){
            return intervals;
        }

        //1. 排序，正序
        Arrays.sort(intervals, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                if (o1[0]==o2[0]){
                    return o1[1]-o2[1];
                }
                return o1[0]-o2[0];
            }
        });

        //2. 定义左右指针
        int l=1,r=2;

        //3. 循环
        while (r<2*intervals.length){
            if (getValue(intervals,r)<=getValue(intervals,l)){
                if (getValue(intervals,l)>getValue(intervals,r+1)){
                    setValue(intervals,r,l-1,false);
                    setValue(intervals,r+1,l,false);
                    setValue(intervals,l,l-1,true);  //标记需要删除的序列
                }else{
                    setValue(intervals,r,l-1,false);
                    setValue(intervals,l,l-1,true);  //标记需要删除的序列
                }
            }
            r+=2;
            l+=2;
        }

        //4. 删去重复的序列（被定义需要删除的序列）
        int index=0;
        for (int i = 0; i < intervals.length; i++) {
            if (check(intervals,i)){
                intervals[index]=intervals[i];
                index++;
            }
        }
        return Arrays.copyOfRange(intervals,0,index);

    }

    public int getValue(int[][] intervals,int index){
        return intervals[index/2][index%2];
    }

    //更新值
    public void setValue(int[][] intervals,int index_a,int index_b,boolean deleted){
        if (deleted){
            intervals[index_a/2][index_a%2]=intervals[index_b/2][index_b%2]-1;
        }else {
            intervals[index_a/2][index_a%2]=intervals[index_b/2][index_b%2];
        }
    }

    //判断是否符合条件
    public boolean check(int[][] intervals,int i){
        if (intervals[i][1]-intervals[i][0]>=0){
            return true;
        }
        return false;
    }





}
